#include<iostream>
#include<string>
#include<algorithm>
#include<map>
#include <vector>
using namespace std;
class Solution {
public:
    class Compare
    {
        public:
        bool operator()(const pair<string, int>& x, const pair<string, int>& y)
        {
            return x.second > y.second || (x.second == y.second && x.first < y.first);
        }
    };
    vector<string> topKFrequent(vector<string>& words, int k) {
        map<string, int> countmap;
        for (auto e: words)
        {
            countmap[e]++;
        }

        vector<pair<string,int>> v(countmap.begin(),countmap.end());
        sort(v.begin(), v.end(), Compare());

        vector<string> strV;
        for (int i = 0; i < k; i++)
        {
            strV.push_back(v[i].first);
        }
        return strV;
    }
};